'use client';

import { useState, useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { Wallet, AlertCircle, Info } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { useAuthStore } from '@/store/auth';
import { useChain } from '@/context/ChainContext';
import { ChainSelector } from '@/components/ui/chain-selector';
import { ChainAuthStatus } from '@/components/auth/ChainAuthStatus';
import { ChainType, isValidChain } from '@/config/chains';
import { ethers } from 'ethers';
import toast from 'react-hot-toast';

declare global {
  interface Window {
    ethereum?: any;
  }
}

// Real MetaMask wallet connection
async function connectWallet(): Promise<string | null> {
  if (!window.ethereum) {
    throw new Error('MetaMask is not installed. Please install MetaMask to continue.');
  }

  try {
    // Request account access
    const accounts = await window.ethereum.request({ 
      method: 'eth_requestAccounts' 
    });
    
    if (accounts.length === 0) {
      throw new Error('No accounts found. Please connect your wallet.');
    }

    // Return the first connected account
    return accounts[0];
  } catch (error: any) {
    if (error.code === 4001) {
      throw new Error('User rejected the wallet connection request.');
    }
    throw new Error('Failed to connect to MetaMask: ' + error.message);
  }
}

async function signMessage(message: string, walletAddress: string): Promise<string> {
  if (!window.ethereum) {
    throw new Error('MetaMask is not available');
  }

  try {
    console.log('Signing message:', message);
    console.log('With wallet:', walletAddress);
    
    // Use personal_sign method which is more compatible with MetaMask
    // Format: personal_sign(message, address)
    const signature = await window.ethereum.request({
      method: 'personal_sign',
      params: [message, walletAddress.toLowerCase()]
    });
    
    console.log('Signature received:', signature);
    return signature;
  } catch (error: any) {
    console.error('Sign message error:', error);
    
    // Handle different error formats
    if (error.code === 4001 || error?.message?.includes('rejected')) {
      throw new Error('User rejected the signature request.');
    }
    
    // Log the full error for debugging
    console.error('Full error object:', JSON.stringify(error, null, 2));
    
    // Extract meaningful error message
    const errorMessage = error?.message || 'Unknown error';
    throw new Error('Failed to sign message: ' + errorMessage);
  }
}

export default function LoginPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { getNonce, login, isAuthenticatedForChain } = useAuthStore();
  const { currentChain, switchChain } = useChain();
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');
  
  // Handle chain parameter from URL
  useEffect(() => {
    const chainParam = searchParams.get('chain');
    if (chainParam && isValidChain(chainParam)) {
      switchChain(chainParam);
    }
  }, [searchParams, switchChain]);
  
  // Check if already authenticated for current chain
  useEffect(() => {
    if (isAuthenticatedForChain(currentChain)) {
      router.push('/dashboard');
    }
  }, [currentChain, isAuthenticatedForChain, router]);

  const handleLogin = async () => {
    setIsLoading(true);
    setError('');

    try {
      // Step 1: Connect wallet
      const walletAddress = await connectWallet();
      if (!walletAddress) {
        throw new Error('Failed to connect wallet');
      }

      console.log('Connected wallet:', walletAddress);
      toast.loading('Connecting to wallet...', { id: 'wallet' });

      // Step 2: Get nonce from backend
      const { message } = await getNonce(walletAddress, currentChain);
      console.log('Received message to sign:', message);
      toast.loading('Please sign the message in MetaMask...', { id: 'wallet' });

      // Step 3: Sign message
      let signature: string;
      try {
        signature = await signMessage(message, walletAddress);
        console.log('Signature received:', signature);
      } catch (signError: any) {
        console.error('Signature error details:', signError);
        
        // Check if it's a user rejection
        if (signError.message.includes('rejected')) {
          throw new Error('You rejected the signature request. Please try again and approve the signature.');
        }
        
        // For other errors, provide more context
        throw new Error(`Failed to sign message: ${signError.message}. Please try again.`);
      }

      // Step 4: Login
      toast.loading('Authenticating...', { id: 'wallet' });
      try {
        await login(walletAddress, signature, currentChain);
        toast.success('Login successful!', { id: 'wallet' });
        router.push('/dashboard');
      } catch (loginError: any) {
        console.error('Backend login error:', loginError);
        
        // Check if it's a non-admin user
        if (loginError.response?.status === 403) {
          throw new Error('Access denied. This wallet is not authorized. Only admin wallets and vesting beneficiaries can access the dashboard.');
        }
        
        throw new Error('Authentication failed. Please ensure your wallet is authorized.');
      }
    } catch (err: any) {
      console.error('Login error:', err);
      setError(err.message || 'Failed to login. Please try again.');
      toast.error('Login failed', { id: 'wallet' });
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="flex min-h-screen items-center justify-center bg-gray-100">
      <Card className="w-full max-w-md">
        <CardHeader className="text-center">
          <div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-blue-100">
            <Wallet className="h-6 w-6 text-blue-600" />
          </div>
          <CardTitle className="text-2xl">Admin Login</CardTitle>
          <CardDescription>
            Connect your MetaMask wallet to access the admin dashboard
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <div className="flex items-center justify-between">
              <label className="text-sm font-medium text-gray-700">
                Select Network
              </label>
              <ChainAuthStatus />
            </div>
            <ChainSelector className="w-full" />
            <div className="mt-2 flex items-start space-x-2 rounded-lg bg-blue-50 p-3 text-sm">
              <Info className="h-4 w-4 text-blue-600 mt-0.5" />
              <div className="text-blue-800">
                <p className="font-medium">Chain-specific authentication</p>
                <p className="text-xs mt-1">Each network requires separate authentication for security. Your authentication status is shown above.</p>
              </div>
            </div>
          </div>
          {error && (
            <div className="flex items-center space-x-2 rounded-lg bg-red-50 p-3 text-sm text-red-600">
              <AlertCircle className="h-4 w-4" />
              <span>{error}</span>
            </div>
          )}

          <Button
            onClick={handleLogin}
            disabled={isLoading}
            className="w-full"
            size="lg"
          >
            {isLoading ? (
              <>
                <span className="mr-2 h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" />
                Connecting...
              </>
            ) : (
              <>
                <Wallet className="mr-2 h-4 w-4" />
                Connect MetaMask Wallet
              </>
            )}
          </Button>

          <div className="text-center text-sm text-gray-500">
            <p>Admin wallets have full access. Vesting beneficiaries can access "My Vesting" page.</p>
            <p className="mt-2 font-mono text-xs">
              Admin wallets: 0x44fafd...bdd6, 0x4e426f...9d50
            </p>
            <p className="mt-1 text-xs text-blue-600">
              Other wallets with vesting allocations can also login for limited access.
            </p>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}